//
//  MusicListViewController.m
//  product_B
//
//  Created by zyc on 16/5/27.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "MusicListViewController.h"
#import "MusicModel.h"
#import "MusicHeaderView.h"
#import "MusicAuthorModel.h"
#import "FirstCellTableViewCell.h"
#import "FirstCellView.h"
#import "SecondCellTableViewCell.h"
#import "ThirdCellTableViewCell.h"
#import "ThirdCellTableViewCell1.h"
#import "ImageLabel.h"
#import "CommentModel.h"
#import "MusicWebViewViewController.h"
#import "MusicViewController.h"
#import "MusicAuthorModel.h"
#import "CommentViewController.h"

@interface MusicListViewController ()<UITableViewDataSource,UITableViewDelegate,ClickDelegate,ThirdDelegate,Third1Delegate>

@property (nonatomic, strong)NSMutableArray *modelArray;

@property (nonatomic, strong)MusicHeaderView *headerView;
@property (nonatomic, strong)NSMutableArray *kindArray;
@property (nonatomic, strong)NSMutableArray *authorArray;
@property (nonatomic, strong)NSMutableArray *commentArray;
@property (nonatomic, assign)BOOL isLike;
@property (nonatomic, assign)NSInteger flag;
@property (nonatomic, strong)NSString *commentID;
@property (nonatomic, strong)FirstCellView *firstHaeder;
@property (nonatomic, strong)FMDBManager *manager;

@end

@implementation MusicListViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _tableView = nil;
    if (_isChild) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 64 + 49) style:UITableViewStylePlain];
        if (self.tabBarController.tabBar.hidden == YES) {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 64 + 49 + 49) style:UITableViewStylePlain];
        }
    }else{
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 64) style:UITableViewStylePlain];
        self.navigationItem.title = @"音乐";
    }
    self.navigationController.navigationBar.translucent = NO;
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    

    [self.view addSubview:_tableView];
    
    _headerView = [[MusicHeaderView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kWidth)];
    //    _headerView.backgroundColor = [UIColor greenColor];
    _musicPlayerView = [[UINib nibWithNibName:@"MusicPlayerView" bundle:nil]instantiateWithOwner:self options:nil].firstObject;
    _musicPlayerView.frame = CGRectMake(20, kWidth - 110, kWidth - 40, 100);
    //    [_musicPlayerView configureWithModel:_model];
    _musicPlayerView.layer.shadowOffset = CGSizeMake(2, 2);
    _musicPlayerView.layer.shadowColor = [UIColor blackColor].CGColor;
    _musicPlayerView.layer.shadowOpacity = 5;
    _musicPlayerView.layer.shadowRadius = 1;
    _musicPlayerView.layer.cornerRadius = 10;
    _musicPlayerView.alpha = 0.8;
    _musicPlayerView.delegate = self;
    
    [_musicPlayerView.button addTarget:self action:@selector(musicAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [_headerView addSubview:_musicPlayerView];
    
    
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 1000;
    _tableView.allowsSelection = NO;
    [_tableView registerNib:[UINib nibWithNibName:@"FirstCellTableViewCell" bundle:nil] forCellReuseIdentifier:@"firstCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"SecondCellTableViewCell" bundle:nil] forCellReuseIdentifier:@"secondCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"ThirdCellTableViewCell" bundle:nil] forCellReuseIdentifier:@"thirdCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"ThirdCellTableViewCell1" bundle:nil] forCellReuseIdentifier:@"thirdCell1"];
    //    [_tableView registerClass:[SecondCellTableViewCell class] forCellReuseIdentifier:@"secondCell"];
    //
    _kindArray = [@[@"音乐故事",@"相似歌曲",@"评论列表"]mutableCopy];
    _authorArray = [NSMutableArray array];
    _commentArray = [NSMutableArray array];
    _flag = 1;
    
    [self request];
    
    _tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        CommentModel *model = _commentArray.lastObject;
        _commentID = [NSString stringWithFormat:@"%@",model.myID];
        if ([_commentID isEqualToString:@"000"]) {
            _commentID = [_commentArray[_commentArray.count - 2] myID];
        }
        [self requestComment];

        [_tableView.mj_footer endRefreshing];
    }];
    
    [self performSelector:@selector(setContent) withObject:nil afterDelay:1];
    _manager = [FMDBManager shareInstance];
    [_manager openDB];
    [_manager createTableNameWithTableName:@"readComment"];
    [_manager deleteReadCommentTableWithTableName:@"readComment" forURL:[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/music/detail/%@",_musicID] myID:@"000"];
}

- (void)click:(UserViewController *)user{
    [self.navigationController pushViewController:user animated:YES];
}

- (void)request{
    NSString *urlString = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/music/detail/%@",_musicID];
    [RequestManager initWithUrlString:urlString requestType:@"GET" parDic:nil finishBlock:^(NSData *data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic = jsonDic[@"data"];
        _model = [[MusicModel alloc]init];
        [_model setValuesForKeysWithDictionary:dic];
        self.navigationItem.title = _model.title;
        [_headerView setViewWithModel:_model];
        _tableView.tableHeaderView = _headerView;
        

        [[MusicPlayerManager shareInstance].musicArray addObject:_model.music_id];
        [MusicPlayerManager shareInstance].url = _model.music_id;
        
        NSMutableArray *array = [MusicPlayerManager shareInstance].musicArray;
        for (NSInteger i = array.count - 1; i > 0; i --) {
            if ([array[i] isEqualToString:array[0]]) {
                [array removeObjectAtIndex:i];
            }
        }

        
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
            
            _musicPlayerView.model = _model;
            [_musicPlayerView configureWithModel:_model];
            [MusicPlayerManager shareInstance].model = _model;
            
        });
    } errorBlock:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    
    NSString *urlMusicString = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/related/music/%@",_musicID];
    [RequestManager initWithUrlString:urlMusicString requestType:@"GET" parDic:nil finishBlock:^(NSData *data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = jsonDic[@"data"];
        
        for (NSDictionary *dic in array) {
            MusicModel *model = [[MusicModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_authorArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [_tableView reloadData];
        });
        
    } errorBlock:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    NSString *commentString = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/comment/praiseandtime/music/%@/0",_musicID];
    [RequestManager initWithUrlString:commentString requestType:@"GET" parDic:nil finishBlock:^(NSData *data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = jsonDic[@"data"][@"data"];
        for (NSDictionary *dic in array) {
            CommentModel *model = [[CommentModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            _manager = [FMDBManager shareInstance];
            
            [_manager insertReadCommentTableWithTableName:@"readComment" url:urlString content:model.content myID:model.myID type:model.type input_date:model.input_date praisenum:model.praisenum quote:model.quote touser_name:model.touser.user_name user_id:model.user.user_id user_name:model.user.user_name web_url:model.user.web_url];
//            [_commentArray addObject:model];
        }
        NSMutableArray *array1 = [_manager selectMusicCommentTableWithTableName:@"readComment" forURL:urlString type:@0];
        NSMutableArray *array2 = [_manager selectMusicCommentTableWithTableName:@"readComment" forURL:urlString type:@1];
        [_commentArray addObjectsFromArray:array1];
        [_commentArray addObjectsFromArray:array2];
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
        });
        
    } errorBlock:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)requestComment{
    NSString *commentString = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/comment/praiseandtime/music/%@/%@",_musicID,_commentID];
    [RequestManager initWithUrlString:commentString requestType:@"GET" parDic:nil finishBlock:^(NSData *data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = jsonDic[@"data"][@"data"];
        for (NSDictionary *dic in array) {
            CommentModel *model = [[CommentModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_commentArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
        });
        
    } errorBlock:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0 ) {
        return 1;
    }else if(section == 2){
        return _commentArray.count;
    }else{
        if (self.authorArray.count != 0) {
            return 1;
        }else{
            return 0;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 ) {
        FirstCellTableViewCell *firstCell = [tableView dequeueReusableCellWithIdentifier:@"firstCell" forIndexPath:indexPath];
        if (_flag == 1) {
            MusicAuthorModel *story = _model.stroyAuthor;
            firstCell.titleOfStory.text = _model.story_title;
            firstCell.authorOfStory.text = story.user_name;
            _model.story = [_model.story stringByReplacingOccurrencesOfString:@"<br>" withString:@""];
            _model.story = [_model.story stringByReplacingOccurrencesOfString:@"<strong>" withString:@""];
            _model.story = [_model.story stringByReplacingOccurrencesOfString:@"</strong>" withString:@""];
            _model.story = [_model.story stringByReplacingOccurrencesOfString:@"<em>" withString:@""];
            _model.story = [_model.story stringByReplacingOccurrencesOfString:@"</em>" withString:@""];
            firstCell.desOfStory.text = _model.story;
            firstCell.charge_edt.text = _model.charge_edt;
        }else if(_flag == 2){
            firstCell.titleOfStory.text = @"歌词";
            firstCell.authorOfStory.text = @"";
            firstCell.desOfStory.text = _model.lyric;
            firstCell.charge_edt.text = @"";
        }else{
            firstCell.titleOfStory.text = @"音乐信息";
            firstCell.authorOfStory.text = @"";
            firstCell.desOfStory.text = _model.info;
            firstCell.charge_edt.text = @"";
        }
        return firstCell;
    }else if(indexPath.section == 1){
        SecondCellTableViewCell *secondCell = [tableView dequeueReusableCellWithIdentifier:@"secondCell" forIndexPath:indexPath];
        if (_authorArray.count >= 3) {
            MusicModel *firstModel = _authorArray[0];
            MusicModel *secondModel = _authorArray[1];
            MusicModel *thirdModel = _authorArray[2];
            [secondCell setFirstWithMusicModel:firstModel];
            [secondCell setSecondWithMusicModel:secondModel];
            [secondCell setThirdWithMusicModel:thirdModel];
            [secondCell.firstButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            [secondCell.secondButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            [secondCell.thirdButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        return secondCell;
    }else{
        CommentModel *model = _commentArray[indexPath.row];
        if (model.touser.user_name == nil) {
            ThirdCellTableViewCell *thirdCell = [tableView dequeueReusableCellWithIdentifier:@"thirdCell" forIndexPath:indexPath];
            [thirdCell cellConfigureWithModel:model];
            thirdCell.delegate = self;
//            if (indexPath.row == 8) {
//                UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kWidth, 2)];
//                label.backgroundColor = [UIColor redColor];
//                [thirdCell addSubview:label];
//            }
            return thirdCell;
        }else{
            ThirdCellTableViewCell1 *thirdCell1 = [tableView dequeueReusableCellWithIdentifier:@"thirdCell1" forIndexPath:indexPath];
            [thirdCell1 cellConfigureWithModel:model];
            thirdCell1.delegate = self;
//            if (indexPath.row == 8) {
//                UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kWidth, 2)];
//                label.backgroundColor = [UIColor redColor];
//                [thirdCell1 addSubview:label];
//            }
            return thirdCell1;
        }
        
        
        
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (_authorArray.count != 0) {
        return _kindArray[section];
    }else{
        if (section == 1) {
            return nil;
        }
        return _kindArray[section];
    }
    
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 0 && kHeight >= 667) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 30)];
        view.backgroundColor = [UIColor whiteColor];
        view.alpha = 0.8;
        
        ImageLabel *like = [[ImageLabel alloc]initWithFrame:CGRectMake(kWidth / 6 - 20, 15, 40, 20) image:[UIImage imageNamed:@"爱心.png"] text:[NSString stringWithFormat:@"%@",_model.praisenum] tapAction:^(UILabel *label, UIImageView *imageView) {
            label.text = [NSString stringWithFormat:@"%ld",label.text.integerValue + 1];
        }];
        [view addSubview:like];
        
        ImageLabel *talk = [[ImageLabel alloc]initWithFrame:CGRectMake(kWidth / 2 - 20, 15, 40, 20) image:[UIImage imageNamed:@"评论.png"] text:[NSString stringWithFormat:@"%@",_model.commentnum] tapAction:^(UILabel *label, UIImageView *imageView) {

            CommentViewController *comment = [[CommentViewController alloc]init];
            comment.url = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/music/detail/%@",_musicID];
            [self.navigationController pushViewController:comment animated:YES];
        }];
        [view addSubview:talk];
        
        ImageLabel *share = [[ImageLabel alloc]initWithFrame:CGRectMake(kWidth / 6 * 5 - 20, 15, 40, 20) image:[UIImage imageNamed:@"分享.png"] text:[NSString stringWithFormat:@"%@",_model.sharenum]  tapAction:^(UILabel *label, UIImageView *imageView) {
            NSString *story;
            //1、创建分享参数
//            NSArray* imageArray = @[[UIImage imageNamed:@"分享.png"]];
            MusicModel *currentModel = [MusicPlayerManager shareInstance].model;
            NSArray *imageArray = @[currentModel.cover];
            // （注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
            if (imageArray) {
                if (currentModel.story.length > 100) {
                    story = [currentModel.story substringToIndex:100];
                }else{
                    story = currentModel.story;
                }
                NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
                [shareParams SSDKSetupShareParamsByText:story
                                                 images:imageArray
                                                    url:[NSURL URLWithString:currentModel.web_url]
                                                  title:currentModel.title
                                                   type:SSDKContentTypeAuto];
                //2、分享（可以弹出我们的分享菜单和编辑界面）//要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                
                [ShareSDK showShareActionSheet:nil
                 
                                         items:nil
                                   shareParams:shareParams
                           onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                               
                               switch (state) {
                                   case SSDKResponseStateSuccess:
                                   {
                                       [self alert:@"分享成功"];
                                       break;
                                   }
                                   case SSDKResponseStateFail:
                                   {
                                       [self alert:@"分享失败"];
                                       break;
                                   }
                                   default:
                                       break;
                               }
                           }
                 ];}
        }];
        [view addSubview:share];
        
        UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(kWidth / 3, 5, 1, 35)];
        label1.backgroundColor = [UIColor grayColor];
        [view addSubview:label1];
        
        UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(kWidth / 3 * 2, 5, 1, 35)];
        label2.backgroundColor = [UIColor grayColor];
        [view addSubview:label2];
        
        UIView *font = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 1)];
        font.backgroundColor = Kcolor(147, 147, 147);
        [view addSubview:font];
        
        UIView *bottom = [[UIView alloc]initWithFrame:CGRectMake(0, 49, kWidth, 1)];
        bottom.backgroundColor = Kcolor(147, 147, 147);
        [view addSubview:bottom];
        
        return view;
    }
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0 && kHeight >= 667) {
        return 50;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        _firstHaeder = [[FirstCellView alloc]init];
        //        _firstHaeder.index = _flag;
        [_firstHaeder.story addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_firstHaeder.lyric addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_firstHaeder.info addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        return _firstHaeder;
    }
    return nil;
}

- (void)buttonAction:(UIButton *)sender{
    if (sender.tag < 10) {
        _flag = sender.tag;
        [_tableView reloadData];
    }else{
        //        MusicWebViewViewController *webView = [[MusicWebViewViewController alloc]init];
        //        webView.myID = [_authorArray[sender.tag - 100]myID];
        //        webView.name = [_authorArray[sender.tag - 100]title];
        //        [self.navigationController pushViewController:webView animated:YES];
        //        [[MusicPlayerManager shareInstance]replaceItemWithUrlString:_model.music_id];
        
        MusicListViewController *listView = [[MusicListViewController alloc]init];
        listView.musicID = [_authorArray[sender.tag - 100]myID];
        listView.isChild = YES;
        [self.navigationController pushViewController:listView animated:YES];
        listView.navigationController.navigationBarHidden = NO;
        listView.navigationController.navigationBar.translucent = NO;
        
    }
    
}

- (void)musicAction:(UIButton *)sender{
    MusicViewController *music = (MusicViewController *)self.parentViewController;
    if (!_isChild) {
        
        
        if ([MusicPlayerManager shareInstance].isPlay) {
            music.musicButton.hidden = NO;
        }else{
            music.musicButton.hidden = YES;
        }
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_isChild) {
        self.navigationController.navigationBar.hidden = NO;
        self.navigationController.navigationBarHidden = NO;
    }
    NSString *urlString = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/music/detail/%@",_musicID];
    [_commentArray removeAllObjects];
    _manager = [FMDBManager shareInstance];
    [_manager openDB];
    NSMutableArray *array1 = [_manager selectMusicCommentTableWithTableName:@"readComment" forURL:urlString type:@0];
    NSMutableArray *array2 = [_manager selectMusicCommentTableWithTableName:@"readComment" forURL:urlString type:@1];
    [_commentArray addObjectsFromArray:array1];
    [_commentArray addObjectsFromArray:array2];
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated{
    _musicPlayerView.isFirst = NO;
}

- (void)loadView{
    [super loadView];
    _tableView = nil;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

- (void)setContent{
    [_tableView setContentOffset:CGPointMake(0, kWidth - 120) animated:YES];
}



- (void)alert:(NSString *)string{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:string preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancel];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
